﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;

using OpenAPI.Web.Mvc.Filter;

namespace OpenAPI.Web.Mvc.Controllers
{
    [ExceptionFilter]
    public class AccountController : Controller
    {

        // **************************************
        // URL: /Account/LogOn
        // **************************************
        [HttpGet]
        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        [ActionName("LogOn")]
        public ActionResult DoLogOn()
        {
            string manage_userid = "";
            string manage_password = "";
            string user_id = Utility.StringHelper.GetPost("txtUSER_ID");
            string password = Utility.StringHelper.GetPost("txtPASSWORD");
            string auth_code = Utility.StringHelper.GetPost("txtAUTH_CODE").ToLower();

            if (string.IsNullOrEmpty(user_id) || string.IsNullOrEmpty(password))
            {
                throw new Exception("User Name、Password不能空");
            }

            if (string.IsNullOrEmpty(auth_code))
            {
                throw new Exception("Validate Code不能空");
            }

            if (Session["ValidateCode"].ToString().Trim() != auth_code.Trim())
            {
                throw new Exception("Validate Code输入不正确");
            }

            bool is_manager = (Request.Form["chkMANAGER"] == "false") ? false : true;

            if (!is_manager)
            {
                Common.Error.ErrorType error = null;
                manage_userid = user_id;
                manage_password = OpenAPI.BLL.OAuth.ConsumerManager.GetOAuthConsumerSecret(manage_userid, out error);
            }
            else
            {
                manage_userid = System.Configuration.ConfigurationManager.AppSettings["MANAGE_USERID"].ToString();
                manage_password = System.Configuration.ConfigurationManager.AppSettings["MANAGE_PASSWORD"].ToString();
            }

            if (user_id != manage_userid || password != manage_password)
            {
                throw new Exception("User Name、Password不正确");
            }

            if (user_id == manage_userid && password == manage_password)
            {
                if (!is_manager)
                {
                    OpenAPI.Model.OAuth.ConsumerInfo consumer = OpenAPI.BLL.OAuth.ConsumerManager.GetConsumer(manage_userid, manage_password);

                    Session["USER_TYPE"] = "Consumer";
                    Session["USER_ID"] = manage_userid;
                    Session["PASSWORD"] = manage_password;
                    Session["USER_NAME"] = consumer.CONSUMER_NAME;
                    Session["ONLINE"] = true;
                }
                else
                {
                    Session["USER_TYPE"] = "Manager";
                    Session["USER_ID"] = manage_userid;
                    Session["PASSWORD"] = manage_password;
                    Session["USER_NAME"] = "Manager";
                    Session["ONLINE"] = true;
                }

                string return_url = Utility.StringHelper.GetQuery("ReturnUrl");
                if (string.IsNullOrEmpty(return_url))
                {
                    return_url = "/";
                }

                Response.Redirect(return_url);
            }

            return View();
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            HttpContext.Session.Clear();
            HttpContext.Session.Abandon();

            return RedirectToAction("Index", "Home");
        }


        #region Validate Code


        public ImageResult ValidateCode()
        {
            return new ImageResult();
        }

        #endregion
    }


    /// <summary>
    /// Validate Code
    /// </summary>
    public class ImageResult : ActionResult
    {
        public string SessionKey { get; set; }

        private const double PI = 3.1415926535897932384626433832795;
        private const double PI2 = 6.283185307179586476925286766559;


        public ImageResult()
        {
            this.SessionKey = "ValidateCode"; //set default ,可设置的目的是防止意外同名情况
        }

        public override void ExecuteResult(ControllerContext context)
        {
            string validateCode = this.CreateCode(5);

            Bitmap img = this.CreateImage(validateCode);
            context.HttpContext.Session[this.SessionKey] = validateCode.ToLower();

            context.HttpContext.Response.ContentType = "image/gif";
            img.Save(context.HttpContext.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
            img.Dispose();
        }


        /// <summary>
        /// 1.生成一个随机的字符串
        /// </summary>
        /// <param name="codeLength"></param>
        /// <returns></returns>
        public string CreateCode(int codeLength)
        {
            //为了减少正常用户的痛苦，把0,O,o这样不容易辨识的字母排除掉。
            //string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            string so = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] strArr = so.Split(',');
            string code = "";
            Random rand = new Random();
            for (int i = 0; i < codeLength; i++)
            {
                code += strArr[rand.Next(0, strArr.Length)];
            }
            return code;
        }

        /// <summary>
        /// 2.根据该随机字符串生成一张位图
        /// </summary>
        /// <param name="checkCode"></param>
        /// <returns></returns>
        private Bitmap CreateImage(string checkCode)
        {
            if (string.IsNullOrEmpty(checkCode.Trim()))
            {
                return null;
            }

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 14.0)), 20);
            Graphics g = Graphics.FromImage(image);

            //生成随机生成器
            Random random = new Random();

            //清空图片背景色
            g.Clear(Color.White);

            //画图片的背景噪音线
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            Font font = new System.Drawing.Font("Arial", 13, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);

            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            //扭曲图片,产生波形
            image = this.TwistImage(image, true, 1, 1);

            return image;
        }


        /// <summary>
        /// 正弦曲线Wave扭曲图片（Edit By 51aspx.com）
        /// </summary>
        /// <param name="srcBmp">图片路径</param>
        /// <param name="bXDir">如果扭曲则选择为True</param>
        /// <param name="nMultValue">波形的幅度倍数，越大扭曲的程度越高，一般为3</param>
        /// <param name="dPhase">波形的起始相位，取值区间[0-2*PI)</param>
        /// <returns></returns>
        private System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

            // 将位图背景填充为白色
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();

            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);

                    // 取得当前点的颜色
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    System.Drawing.Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width
                     && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }

            return destBmp;
        }


    }//

}
